<!--
  @Descripttion:：全局header
  @Author：yejianbo
  @Date：2022年05月26日 12:35:40
-->
<template>
  <div>
  <section class="header-com">
    <div class="center">
      <div class="logo">
        <img
          src="@/assets/images/home/logo.png"
          @click="menuHandle('home')"
          v-imgError
          alt=""
        />
      </div>
      <div class="menu">
        <ul>
          <li
            :class="[
              { current: currentRoute === '/home' || currentRoute === '/' },
            ]"
            @click="menuHandle('home')"
          >
            首页
          </li>
          <li
            :class="[{ current: currentRoute === '/hire' }]"
            @click="menuHandle('hire')"
          >
            招聘专区
          </li>
          <li
            :class="[
              {
                current:
                  currentRoute === '/studentStyle' ||
                  currentRoute === '/studentStyleDetails',
              },
            ]"
            @click="menuHandle('studentStyle')"
          >
            学生风采
          </li>
          <!-- <li :class="[{ current: currentRoute === '/newsAction' || currentRoute.indexOf('/searchResultDetail/news') > -1}]" @click="menuHandle('newsAction')">
            前沿资讯
          </li> -->
          <!-- <li :class="[{ current: currentRoute === '/researchResult' ||
            currentRoute === '/resultList' ||
            currentRoute.indexOf('/searchResultDetail/search') > -1}]" @click="menuHandle('researchResult')">
            研究成果
          </li> -->
          <!-- <li :class="[{ current: currentRoute === 3 }]" @click="menuHandle()">
            实践项目
          </li>
          <li :class="[{ current: currentRoute === 4 }]" @click="menuHandle()">
            前沿资讯
          </li>
          <li :class="[{ current: currentRoute === 5 }]" @click="menuHandle()">
            研究成果
          </li> -->
          <li
            :class="[
              {
                current:
                  currentRoute === '/cultivate?type=2&url=companyProfile',
              },
            ]"
            @click="openPage('cultivate', { type: 2, url: 'companyProfile' })"
          >
            关于我们
          </li>
        </ul>
      </div>
      <div class="operation">
        <!--<div
          class="search-icon"
          slot="reference"
          @click.stop="openSearch"
        ></div>-->
        <span
          class="btn"
          @click="linkTo('https://www.datarer.com/admin/#/login')"
          v-if="!userMobile"
          >我要招聘</span
        >
        <span class="btn" @click="menuHandle('login')" v-if="!userMobile"
          >我要实习</span
        >
        <el-dropdown v-if="userMobile" @command="handleCommand">
          <div class="user-info">
            <div class="tips" v-if="nums1 + nums2 + nums3 > 0">
              {{ fetchNums(nums1 + nums2 + nums3) }}
            </div>
            <img
              class="user-img"
              v-if="userInfo && userInfo.studentPictureUrl"
              :src="userInfo.studentPictureUrl"
              alt=""
              @click="menuHandle('userCenter')"
            />
            <img
              class="user-img"
              v-else
              src="@/assets/images/home/user_img.png"
              alt=""
              @click="menuHandle('userCenter')"
            />
            <span class="el-dropdown-link btn">
              {{
                userInfo && userInfo.studentName ? userInfo.studentName : "游客"
              }}
              <!--<i class="el-icon-arrow-down el-icon--right"></i>-->
            </span>
          </div>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item command="userCenter">个人中心</el-dropdown-item>
            <el-dropdown-item command="invited"
              >面试邀约
              <span v-if="nums1 > 0">{{
                fetchNums(nums1)
              }}</span></el-dropdown-item
            >
            <el-dropdown-item command="feedback"
              >应聘反馈
              <span v-if="nums2 > 0" class="orange">{{
                fetchNums(nums2)
              }}</span></el-dropdown-item
            >
            <el-dropdown-item command="inboxNotifications"
              >站内信<span v-if="nums3 > 0" class="orange">{{
                fetchNums(nums3)
              }}</span></el-dropdown-item
            >
            <el-dropdown-item command="logOut">退出</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
        <img
          class="user-img"
          v-else
          src="@/assets/images/home/user_img.png"
          alt=""
          @click="menuHandle('userCenter')"
        />
      </div>
    </div>
    <el-dialog
      :visible.sync="showSearch"
      title="关键字搜索"
      width="340px"
      append-to-body
    >
      <el-row type="flex" @click.stop="showSearch = true">
        <el-col>
          <el-select
            v-model="headSearchType"
            style="width: 80px"
            @change="searchFocus"
          >
            <el-option value="1" label="企业" style="font-size: 14px"
              >企业</el-option
            >
            <el-option value="2" label="职位" style="font-size: 14px"
              >职位</el-option
            >
          </el-select>
        </el-col>
        <el-col>
          <el-input
            ref="searchInput"
            v-model="headKeyword"
            placeholder="请输入内容后回车搜索"
            @keypress.enter.native="searchTitle"
            style="width: 220px"
          />
        </el-col>
      </el-row>
    </el-dialog>
  </section>
  <MobliePage
    :userInfo="userInfo"
    @menuHandle="menuHandle"
    @openPage="openPage"
    @handleCommand="handleCommand"
  />
  </div>
</template>

<script>
import {
  getStudentCurriculumVitaeBylogin,
  getNums,
  getNums2,
  getInnerMsgNum,
} from "../../request/api";
import { Message } from "element-ui";
import { mapMutations, mapActions, mapState } from "vuex";
import MobliePage from './mobile/index.vue';
export default {
  // 组件名称
  name: "demo",
  // 组件状态值
  data() {
    return {
      headSearchType: "1", // 搜索类型 1 企业 2 职位 3 项目
      currentRoute: "",
      userInfo: {},
      showSearch: false,
      headKeyword: "",
      nums1: 0,
      nums2: 0,
      nums3: 0,
      sums: 0,
      setInter: null,
      innerMsgTimer: null,
      setInterTime: 0,
    };
  },
  components: { MobliePage },
  // 计算属性
  computed: {
    ...mapState(["USER_INFO", "userMobile"]),
  },
  watch: {
    USER_INFO: function (newValue, oldValue) {
      this.userInfo = newValue;
    },
    $route: {
      handler(val) {
        if (val) {
          document.title = val.meta.title;
          this.currentRoute = this.$route.fullPath;
          this.init();
        }
      },
      deep: true,
      immediate: true,
    },
  },
  // 组件方法
  methods: {
    openPage(routeName, query) {
      this.$router.push({ name: routeName, query: { ...query } });
    },
    openSearch() {
      if (this.showSearch) {
        // this.closeSearch()
        return;
      }
      this.showSearch = true;
      this.headKeyword = "";
    },
    // 关闭搜索框
    closeSearch() {
      this.showSearch = false;
    },
    searchFocus() {
      this.$nextTick(() => {
        this.$refs.searchInput.focus();
      });
    },
    // 搜索1 企业、2 职位、3 项目标题
    searchTitle() {
      let type = Number(this.headSearchType);
      this.closeSearch();
      switch (type) {
        case 1:
          this.$router.push({
            path: "/companyList",
            query: { keyword: this.headKeyword },
          });
          break;
        case 2:
          this.$router.push({
            path: "/jobList",
            query: { keyword: this.headKeyword },
          });
          break;
      }
    },
    linkTo(url) {
      window.open(url, "_blank");
    },
    ...mapMutations(["loginOut"]),
    handleCommand(command) {
      if (command === "logOut") {
        this.$confirm("是否确认退出当前账号?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
        }).then(() => {
          this.loginOut(() => {
            this.$router.push({ name: "login" });
          });
        });
      } else {
        this.$router.push({ name: command });
      }
    },

    async init() {
      let studentId = localStorage.getItem("userId");
      if (!studentId) return;
      if (this.setInter !== null) {
        clearInterval(this.setInter);
        this.setInter = null;
        this.setInterTime = 0;
      }
      this.setInter = setInterval(() => {
        this.setInterTime += 1;
        if (this.setInterTime >= 60 * 5) {
          this.setInterTime = 0;
          this.init();
          clearInterval(this.setInter);
          this.setInter = null;
        }
      }, 1000);
      const res1 = await getNums({ studentId });
      if (res1.code === 0) {
        this.nums1 = res1.data;
        // this.sums = this.sums + res1.data
      }
      const res2 = await getNums2({ studentId });
      if (res2.code === 0) {
        this.nums2 = res2.data;
        // this.sums = this.sums + res2.data;
      }
      const { code, data } = await getInnerMsgNum();
      if (code === 0) {
        this.nums3 = Number(data);
      } else {
        this.nums3 = 0;
      }
    },
    fetchNums(num) {
      if (!num) return 0;
      return num >= 100 ? "99+" : num;
    },
    menuHandle(routeName) {
      console.log('routeName',routeName)
      if (!routeName) {
        Message.info({
          message: "模块开发中，即将上线，敬请期待",
          duration: 1000,
        });
        return;
      }
      if (
        !this.userMobile &&
        [
          "login",
          "home",
          "studentStyle",
          "newsAction",
          "researchResult",
          "hire",
        ].indexOf(routeName) === -1
      ) {
        Message.error({ message: "请先登录", duration: 1000 });
        this.$router.push({ name: "login" });
        return;
      }
      this.$router.push({ name: routeName });
    },
  },
  created() {
    getStudentCurriculumVitaeBylogin().then((res) => {
      // bug 如果新用户没有简历，这里设置userId失败，会导致接口请求异常
      if (res.data && res.data.length > 0) {
        this.$store.commit("setUserId", res.data[0].studentId);
        this.$store.commit("setCurriculumId", res.data[0].id);
        // localStorage.setItem('curriculumId',res.data.id)
        this.init();
      }
    });
    !this.userInfo?.studentName && this.$store.dispatch("FETCH_USER_INFO");
    // this.getInnerMsgNum();
  },
  activated() {
    getStudentCurriculumVitaeBylogin().then((res) => {
      if (res.data && res.data.length > 0) {
        this.$store.commit("setUserId", res.data[0].studentId);
        this.$store.commit("setCurriculumId", res.data[0].id);
        // localStorage.setItem('curriculumId',res.data.id)
        this.init();
      }
    });
    !this.userInfo?.studentName && this.$store.dispatch("FETCH_USER_INFO");
  },
  destroyed() {
    clearInterval(this.setInter);
    clearInterval(this.innerMsgTimer);
  },
};
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang='less' scope>
@media screen and (max-width: 750px) {
  #app {
    min-width: auto;
  }
  .header-com {
    display: none !important;
  }
  .mobile-header-page {
    display: block !important;
  }
  .el-message-box {
    width: 80% !important;
  }
}
</style>
<style lang="less" scoped>
.header-com {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  min-width: 1000px;
  height: 80px;
  background-color: #fff;
  border-bottom: 1px solid #d4d6da;
  z-index: 999;
  box-shadow: 0px 4px 17px 0px rgba(0, 0, 0, 0.08);
  .center {
    position: relative;
    width: 1200px;
    // width: calc(100% - 220px);
    // min-width: 1000px;
    // max-width: 1200px;
    height: 100%;
    margin: 0 auto;
    display: flex;
    justify-content: flex-start;
    flex-flow: row nowrap;
    background-color: #fff;
  }
  .logo {
    position: relative;
    height: 100%;
    display: flex;
    flex-flow: flex-start;
    align-items: center;
    // padding-right: 50px;
    // &:after {
    //   content: "";
    //   display: block;
    //   width: 1px;
    //   height: 52px;
    //   background: #d2d2d2;
    //   position: absolute;
    //   top: 50%;
    //   transform: translateY(-50%);
    //   right: 0;
    // }
    img {
      position: relative;
      display: block;
      width: 57px;
      height: 52px;
    }
  }
  .menu {
    ul {
      position: relative;
      display: flex;
      flex-flow: row nowrap;
      align-items: center;
      height: 80px;
      text-align: left;
      padding-left: 30px;
      li {
        position: relative;
        display: inline-block;
        font-size: 16px;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: #3d6cb0;
        line-height: 24px;
        margin: 0 20px;
        vertical-align: bottom;
        transition-duration: 0.3s;
        cursor: pointer;
        &:hover {
          font-size: 20px;
          font-weight: 600;
          color: #15539a;
          &:after {
            content: "";
            display: blcok;
            position: absolute;
            bottom: -5px;
            left: 0;
            width: 100%;
            height: 2px;
            background: #15539a;
          }
        }
      }
      .current {
        font-size: 20px;
        font-family: PingFangSC-Semibold, PingFang SC;
        font-weight: 600;
        color: #15539a;
        line-height: 24px;
        vertical-align: bottom;
        &:after {
          content: "";
          display: blcok;
          position: absolute;
          bottom: -5px;
          left: 0;
          width: 100%;
          height: 2px;
          background: #15539a;
        }
      }
    }
  }
  .operation {
    flex: 1;
    height: 100%;
    display: flex;
    flex-flow: row nowrap;
    justify-content: flex-end;
    align-items: center;
    .search-icon {
      position: relative;
      display: inline-block;
      width: 26px;
      height: 26px;
      background: url("../../assets/images/home/search-icon.png") no-repeat
        center center / cover;
      vertical-align: middle;
      cursor: pointer;
      margin-right: 20px;
    }
    .btn {
      display: inline-block;
      font-size: 14px;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color: #4677b9;
      line-height: 24px;
      margin-right: 20px;
      vertical-align: middle;
      cursor: pointer;
      &:last-child {
        margin-right: 0;
      }
    }
    .btn:hover {
      font-weight: bold;
    }
    .user-img {
      // display: inline-block;
      width: 38px;
      height: 38px;
      border-radius: 4px;
      vertical-align: middle;
      cursor: pointer;
      margin-right: 15px;
    }
    .user-info {
      display: flex;
      // flex-flow: column nowrap;
      justify-content: center;
      align-items: center;
      position: relative;
      .tips {
        padding: 0px 5px;
        font-size: 12px;
        color: #fff;
        line-height: 17px;
        border-radius: 100px;
        position: absolute;
        top: -7px;
        left: 30px;
        background: red;
      }
    }
  }
}
/deep/ .el-dropdown-menu__item {
  span {
    font-size: 12px;
    font-family: PingFangSC-Medium, PingFang SC;
    color: #ffffff;
    line-height: 17px;
    padding: 0 5px;
    border-radius: 15px;
    background: #fe4e3d;
    margin-left: 15px;
    &.orange {
      background: rgb(252, 156, 33);
    }
  }
}
// @media only screen and (max-width: 1500px) {
//   .center {
//     // width: 1000px !important;
//     .logo {
//       padding-right: 20px;
//     }
//     .menu {
//       ul {
//         position: relative;
//         display: flex;
//         flex-flow: row nowrap;
//         align-items: center;
//         height: 100px;
//         padding-left: 10px;
//         text-align: left;
//         li {
//           margin: 0 10px;
//           font-size: 16px;
//         }
//       }
//     }
//     .operation {
//       .search-icon {
//         width: 24px;
//         height: 24px;
//         margin-right: 10px;
//       }
//       .btn {
//         font-size: 18px;
//       }
//       .user-img {
//         width: 30px;
//         height: 30px;
//       }
//     }
//   }
// }
</style>
